import {
  get,
  post
} from '../../utils/request'
import {
  APIS
} from '../../utils/api'
Page({
  data: {
    used: 0,
    type: 'recharge',
    currShop: {},
    orderList: []
  },
  onLoad(opt) {
    const currShop = wx.getStorageSync('currShop')
    this.setData({
      type: opt.type,
      currShop
    })
  },
  onShow() {
    this.getSwitch();
  },

  handelTab(e) {
    let used = e.target.dataset.key;
    if (used === this.data.used) {
      return;
    }
    this.setData({
      used
    }, () => {
      this.getSwitch()
    })
  },
  getSwitch() {
    const type = this.data.type;
    if (type === 'recharge') {
      this.getRecharge();
    } else if (type === 'discount') {
      this.getDiscount();
    }
  },
  getRecharge() {
    let {
      currShop,
      used: used
    } = this.data;
    get(APIS.recharge, {
      shop: currShop.id,
      used
    }).then(res => {
      const list = res.data;
      this.setData({
        orderList: list.map(x => {
          return {
            ...x,
            title: `充值${x.amount}元 送${x.presentation}元`,
            rule: `充值${x.amount}元 送${x.presentation}元`,
            time: `${x.start} ~ ${x.end}`
          }
        })
      });
    })
  },
  getDiscount() {
    let {
      currShop,
      used: used
    } = this.data;
    get(APIS.discount, {
      shop: currShop.id,
      used
    }).then(res => {
      const list = res.data;
      this.setData({
        orderList: list.map(x => {
          return {
            ...x,
            title: x.alias,
            rule: x.alias,
            time: `${x.start} ~ ${x.end}`
          }
        })
      });
    })
  },
  handleJump(e) {
    let {
      info
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/distribution/index?id=${info.id}`
    })
  },
  handleJumpCreate(e) {
    wx.navigateTo({
      url: `/pages/rechargenew/index?type=${this.data.type}`
    })
  },
  handleShopChange(e) {
    const currShop = e.detail;
    this.setData({
      currShop
    }, () => {
      this.getSwitch();
    });
  },
  handleJumpDetail(e) {
    const {
      item
    } = e.target.dataset;
    let {
      used,
      type
    } = this.data;
    if (used) {
      wx.navigateTo({
        url: `/pages/rechargenew/index?type=${type}&action=modify&id=${item.id}`,
      })
    }
    else {
      wx.navigateTo({
        url: `/pages/rechargedetail/index?type=${type}&id=${item.id}`,
      })
    }
  }
})